package com.kim.producers.config;

import com.kim.producers.callback.RabbitConfirmCallback;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * rabbitmq 配置
 *
 * @author huan.fu
 * @date 2018/11/5 - 13:45
 */
@Configuration
public class RabbitmqConfiguration {

    /**
     * exchange交换器名字
     */
    @Value("${rabbitmq.driver.exchange}")
    private String driverUpExchangeName;
    /**
     * 路由键名字
     */
    @Value("${rabbitmq.driver.routingkey}")
    private String driverUpRoutingKey;
    /**
     * queue
     */
    @Value("${rabbitmq.driver.queue}")
    private String driverUpQueue;
    /**
     * 死信交换机
     */
    @Value("${rabbitmq.dlx.exchange}")
    private String dlxExchange;
    /**
     * 死信队列
     */
    @Value("${rabbitmq.dlx.queue}")
    private String dlxQueue;
    /**
     * 死信路由
     */
    @Value("${rabbitmq.dlx.routingKey}")
    private String dlxRoutingKey;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        // 设置生产者消息确认
        rabbitTemplate.setConfirmCallback(new RabbitConfirmCallback());
    }


    //死信交换机
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(dlxExchange);
    }


    //声明死信队列 (真正的队列)

    @Bean
    public Queue dlxQueue() {
        return new Queue(dlxQueue);
    }

    /**
     * 声明订单业务交换机(基本交换机)
     */
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(driverUpExchangeName);
    }

    /**
     * 声明订单队列（用于基本交换机和基本路由到死信队列的绑定）
     */
    @Bean
    public Queue orderQueue() {
        Map<String, Object> arguments = new HashMap<>(2);
        // 绑定我们的死信交换机
        arguments.put("x-dead-letter-exchange", dlxExchange);
        // 绑定我们的路由key
        arguments.put("x-dead-letter-routing-key", dlxRoutingKey);
        return new Queue(driverUpQueue, true, false, false, arguments);
    }

    /**
     * (创建基本交换机+基本路由 -> 死信队列 的绑定)
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(driverUpRoutingKey);
    }

    /**
     * （死信交换机+死信路由->真正队列 的绑定）
     */
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(dlxRoutingKey);
    }
}
